package com.thread.pool.application.scanner.factory;

import com.thread.pool.application.scanner.execute.AnnotationScanner;
import com.thread.pool.application.scanner.model.ActionEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author Ldanniel
 */
public class ActionHandleFactory implements Callable<Map<String, Object>> {
    private static final Logger logger = LoggerFactory.getLogger(ActionHandleFactory.class);
    private Map<String, Object> paramMap;
    private String policy;
    private ReentrantReadWriteLock.WriteLock writeLock;

    public ActionHandleFactory(Map<String, Object> paramMap, String policy, ReentrantReadWriteLock.WriteLock writeLock) {
        this.paramMap = paramMap;
        this.policy = policy;
        this.writeLock = writeLock;
    }

    @Override
    public Map call() throws Exception {
        return annotationScanner(paramMap, policy);
    }

    /**
     * 扫描注解的入口，统一由工厂处理
     *
     * @throws Exception
     */

    public Map<String, Object> annotationScanner(Map<String, Object> paramMap, String policy) throws Exception {
        try{
            writeLock.lock();
            Thread.sleep(3000);
            logger.info("开始执行annotationScanner方法");
            ActionEntity actionEntity = (ActionEntity) paramMap.get(policy);
            Class<?> klass = actionEntity.getKlass();
            Method method = klass.getMethod(actionEntity.getMethod().getName(), Map.class);
            Object invoke = method.invoke(actionEntity.getExecuteMethod(), paramMap);

            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("threadName", Thread.currentThread().getName());
            resultMap.put("invoke", invoke);
            resultMap.put("status", "当前任务已经执行完毕");
            System.out.println("当前执行线程的名称为：" + Thread.currentThread().getName());
            System.out.println(resultMap);
            writeLock.unlock();
            return resultMap;
        }catch (Exception e){

        }
        return null;
    }
}
